/*
 *
 *  *    Copyright 2020-2021 luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.core.utils;

/**
 * The type Date util.
 *
 * @author luter
 */
public abstract class DateUtil {
    /**
     * Instantiates a new Date util.
     */
    private DateUtil() {
    }

    /**
     * 以友好格式显示时间差
     *
     * @param milliseconds 时间差值毫秒数
     * @return the string  "%d days, %d hours, %d minutes, %d seconds ,%d seconds millis"
     */
    public static String niceDuration(long milliseconds) {
        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long elapsedDays = milliseconds / daysInMilli;
        milliseconds = milliseconds % daysInMilli;

        long elapsedHours = milliseconds / hoursInMilli;
        milliseconds = milliseconds % hoursInMilli;

        long elapsedMinutes = milliseconds / minutesInMilli;
        milliseconds = milliseconds % minutesInMilli;

        long elapsedSeconds = milliseconds / secondsInMilli;
        if (elapsedDays > 0) {
            return String.format("%d days, %d hours, %d minutes, %d seconds",
                    elapsedDays,
                    elapsedHours, elapsedMinutes, elapsedSeconds);
        }
        if (elapsedHours > 0) {
            return String.format(" %d hours, %d minutes, %d seconds",
                    elapsedHours, elapsedMinutes, elapsedSeconds);
        }
        if (elapsedMinutes > 0) {
            return String.format(" %d minutes, %d seconds",
                    elapsedMinutes, elapsedSeconds);
        }
        if (elapsedSeconds > 0) {
            return String.format(" %d seconds",
                    elapsedSeconds);
        }
        return milliseconds + " millis.";

    }

    /**
     * 格式化当前时间
     *
     * @return the string
     */
    public static String now() {
        return formatMillis(System.currentTimeMillis());
    }

    /**
     * 毫秒格式化
     * <p>
     * 格式:年月日 时分秒
     *
     * @param millis the millis
     * @return the string
     */
    public static String formatMillis(long millis) {
        return String.format("%tF %<tT", millis);
    }
}
